package com.cfs.config.filter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.stereotype.Component;

import com.cfs.utils.WebUtils;
import com.xiaoleilu.hutool.json.JSONObject;

/**
 * Created by Administrator on 2017/9/27/027.
 */
@Component
public class CustomFormAuthenticationFilter extends FormAuthenticationFilter {

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {

        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        Subject subject = SecurityUtils.getSubject();
        if(!subject.isAuthenticated()){
            if(WebUtils.isAjax(req)){
                resp.setCharacterEncoding("UTF-8");
                JSONObject rj = new JSONObject();
                rj.put("msg", "expire");
                rj.put("code", 0);
                String sj = rj.toString();
                resp.setContentLength(sj.length());
                resp.getWriter().write(sj);
                resp.flushBuffer();
                return false;
            }else{
                return super.onAccessDenied(request, response);
            }
        }
        return true;
    }


    @Override
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {
        return super.onLoginSuccess(token, subject, request, response);
    }
}
